﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAL
{
    public partial class ExpenseLineSimple : IGetValue
    {
        public decimal GetExpenseValue()
        {
            return Convert.ToDecimal(this.Value);
        }

        public static ExpenseLineSimple Get(Guid id)
        {
            DataAccessDataContext dc = new DataAccessDataContext();
            IQueryable<ExpenseLineSimple> q = from e in dc.ExpenseLineSimples
                    where e.Id.Equals(id)
                    select e;
            int count = q.Count();
            if (count == 0)
                return null;
            return q.First<ExpenseLineSimple>();
        }

        public void Save()
        {
            using (DataAccessDataContext dc = new DataAccessDataContext())
            {
                var q = from els in dc.ExpenseLineSimples
                        where els.Id.Equals(this.Id)
                        select els;
                int count = q.Count<ExpenseLineSimple>();
                ExpenseLineSimple exp = null;
                if (count == 1)
                    exp = q.First<ExpenseLineSimple>();
                if (exp == null)
                {
                    var query = from e in dc.ExpenseLines
                                where e.Id.Equals(this.Id)
                                select e;
                    ExpenseLine expLine = query.Single<ExpenseLine>();
                    expLine.Value = this.GetExpenseValue();
                    dc.ExpenseLineSimples.InsertOnSubmit(this);
                }
                else
                {
                    //exp = new ExpenseLineSimple();
                    exp.Value = this.Value;
                    exp.ExpenseLine.Value = this.GetExpenseValue();
                }
                dc.SubmitChanges();
            }
        }
    }
}
